/*
 * Copyright (C) 2007-2012 by XDEV Software, All Rights Reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 3.0 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
 
package xdev.util;


import java.awt.Color;

import xdev.lang.LibraryMember;


/**
 * 
 * <p>
 * The <code>ColorUtils</code> class provides utility methods for {@link Color}
 * handling.
 * </p>
 * 
 * @author XDEV Software
 * 
 * @since 2.0
 */
@LibraryMember
public final class ColorUtils
{
	private ColorUtils()
	{
	}
	

	/**
	 * Creates an sRGB color with the RGB values of the <code>original</code>
	 * and the specified <code>alpha</code> value.
	 * 
	 * 
	 * @param original
	 *            the original {@link Color}
	 * @param alpha
	 *            the alpha component (range 0 - 255)
	 * 
	 * @return the new created color
	 * 
	 * @throws IllegalArgumentException
	 *             if <code>alpha</code> are outside of the range 0 to 255,
	 *             inclusive
	 * 
	 * @see Color
	 */
	public static Color deriveColor(Color original, int alpha) throws IllegalArgumentException
	{
		return new Color(original.getRed(),original.getGreen(),original.getBlue(),alpha);
	}
	

	/**
	 * Creates a color from the average values of the given <code>c1</code> and
	 * <code>c2</code>.
	 * 
	 * @param c1
	 *            first color
	 * @param c2
	 *            second color
	 * 
	 * @return the {@link Color} with the average values
	 */
	public static Color getMiddle(Color c1, Color c2)
	{
		int r = c1.getRed();
		int g = c1.getGreen();
		int b = c1.getBlue();
		
		int rd = (c2.getRed() - r) / 2;
		int gd = (c2.getGreen() - g) / 2;
		int bd = (c2.getBlue() - b) / 2;
		
		return new Color(r + rd,g + gd,b + bd);
	}
	

	// TODO javadoc
	public static Color getDifference(Color c1, Color c2, float pos)
	{
		return new Color(getColorPos(c1.getRed(),c2.getRed(),pos),getColorPos(c1.getGreen(),
				c2.getGreen(),pos),getColorPos(c1.getBlue(),c2.getBlue(),pos));
	}
	

	private static int getColorPos(int i1, int i2, float pos)
	{
		int max = Math.max(i1,i2);
		int min = Math.min(i1,i2);
		
		return min + Math.round((max - min) * pos);
	}
}
